import wx
import common
import rex
class objectInspector(wx.MiniFrame):
	def __init__(
		self, parent, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
		style=wx.DEFAULT_FRAME_STYLE 
		):
		self.rexObject = None
		self.variables = {}
		wx.MiniFrame.__init__(self, parent, -1, title, pos, size, style)
		#panel = wx.Panel(self, -1)
		sizer = wx.BoxSizer( wx.VERTICAL )
		self.var_list= wx.ListCtrl( self, -1, style=wx.LC_SINGLE_SEL | wx.LC_REPORT )
		# Create the column header
		info = wx.ListItem()
		info.m_mask = wx.LIST_MASK_TEXT # | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
		info.m_image = -1
		info.m_format = 0
		info.m_text = "Variable"
		self.var_list.InsertColumnInfo(0, info)
		info.m_text = "Value"
		self.var_list.InsertColumnInfo(1, info)
		# Set the events
		#.Bind( wx.EVT_LEFT_DCLICK( self.list, self.OnActivateAccount )
		self.var_list.Bind( wx.EVT_LIST_ITEM_SELECTED, self.OnVariableSelected )
		self.var_list.Bind( wx.EVT_LIST_ITEM_ACTIVATED, self.OnVariableActivated )
		sizer.Add( self.var_list,1,wx.EXPAND)
		self.pubsOk= ['id','created_on','name','layout','title','description']
		self.isssOk= ['id','created_on','name','title','description','publication_id']
		# button = wx.Button(self, -1, "Close Me")
		# self.Bind(wx.EVT_BUTTON, self.OnCloseMe, button)
		# self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
		# sizer.Add( button,0,0)
		self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
		self.SetSizer(sizer)
		
	def OnVariableSelected(self,event):
		# common.dprint("Variable Selected", event)
		# common.dprint("Variable Selected", event.GetIndex())
		# common.dprint("Variable Selected", event.GetItem())
		# common.dprint(self.variables)
		# item = event.GetItem()
		# common.dprint(item)
		# varId = self.var_list.GetItemData(event.GetIndex())
		# common.dprint(varId)
		varId = event.GetData()
		var = self.variables[varId]
		#common.dprint(var)
		
	def OnVariableActivated(self,event):
		common.dprint("Variable Activated", event)
		varId = event.GetData()
		var = self.variables[varId]
		common.dprint(var)
		self.OpenObject(event, var['name'])
		
	def OpenObject(self,event, variable):
		common.dprint("Opening [%s]" %variable, self.rexObject.__class__, self.rexObject.module)
		module = self.rexObject.module.lower()
		if module == 'newsletter':
			module = 'news'
		elif module == 'email':
			module = 'mail'
		elif module == 'base':
			module = 'web'
		if self.rexObject.__class__ == rex.publications.publication:
			pb=("pubs-%s" % module, self.rexObject['id'],"%s.espx"%variable)
		elif self.rexObject.__class__ == rex.publications.issue:
			pb=("issues-%s" % module, self.rexObject['id'],"%s.espx"%variable)
		elif self.rexObject.__class__ == rex.contacts.contact:
			# temp fix			
			cro = ['uuid','id','xid']
			ext = 'espx'
			if variable in cro:
				ext = 'readonly'
			pb=("contacts", self.rexObject['uuid'],"%s.%s"%(variable,ext))
		elif self.rexObject.__class__ == rex.binders.instance:
			# temp fix
			cro = ['instance_id','created_on','modtime']
			ext = 'espx'
	
			if variable in cro:
				ext = 'readonly'
			pb = ('binder-%s'% self.rexObject.binder['id'], self.rexObject['instance_id'], "%s.%s"%(variable,ext))
		common.dprint("Path Bits", pb)
		if len(pb) == 0:
			common.dprint("Object not recognized")
			return
		self.rexObject.account.coordinator.addFileSet(pb)
		self.rexObject.account.coordinator.openFile(pb)
		
	def setObject(self, rexObject):
		self.rexObject = rexObject
		self.variables = {}
		self.var_list.DeleteAllItems()
		objectVars = []
		if self.rexObject.__class__ == rex.contacts.contact or self.rexObject.__class__ == rex.binders.instance:
			binder_id = 'CONTACT'
			if self.rexObject.__class__ == rex.binders.instance:
				binder_id = self.rexObject.binder['id']
			common.dprint("Getting binder variables for binder ", binder_id)
			bVars = self.rexObject.account.window.binder_control.getBinderVariables(binder_id)
			for variable in bVars:
				if variable['name'] == '__eas__modtime' or variable['name'] == 'id' or variable['name'] == 'instance_id' or variable['name'] == 'trashed_on': continue
				bVar = {'label':variable['name'].lower(),'value':'...','name':variable['name'].lower(),'custom':False}
				objectVars.append(bVar)
		else:
			objectVars = self.rexObject.data
		for variable in objectVars:
			# don't add id and instance_id variables
			if variable['name'] == '__eas__modtime' or variable['name'] == 'id' or variable['name'] == 'instance_id' or variable['name'] == 'trashed_on': continue
			self.appendVariable( variable )
		wx.Yield()
		if self.rexObject.__class__ != rex.dav.dav_item:
			if self.rexObject.__class__ == rex.contacts.contact or self.rexObject.__class__ == rex.binders.instance:
				self.var_list.SortItems( self.sortVariables )
				self.colorVariables()

	def appendVariable( self, variable ):
		# Skip some variables
		if self.rexObject.__class__ != rex.dav.dav_item:
			if self.rexObject.module.lower() == 'web':
				skip = ['reply_email','cc_email','bcc_email','bouncer','bouncer_group','bouncer_email',
						'delivery', 'delivery_day', 'delivery_date','status','recurrence_rule',
						'recurrence_variable','archived_on']
				if variable['name'] in skip: return
		variableValue = unicode(variable['value'])
		if self.rexObject.__class__ == rex.publications.publication and (variable['name'] not in self.pubsOk):
			variableValue = '...'
		elif self.rexObject.__class__ == rex.publications.issue and (variable['name'] not in self.isssOk):
			variableValue = '...'
		item = self.var_list.InsertStringItem( len(self.variables), unicode(variable['label']) )
		self.var_list.SetStringItem( item, 1, variableValue )
		#common.dprint("Variable value", variable['value'])
		var_id = abs( id( variable ) )
		self.var_list.SetItemData( item, var_id )
		self.var_list.SetColumnWidth( 0, wx.LIST_AUTOSIZE )
		self.var_list.SetColumnWidth( 1, wx.LIST_AUTOSIZE )
		self.variables[ var_id ] = variable
		# Select the id by default
		if 	variable['name'] == 'header' and isinstance( self.rexObject, rex.publications.publication ):
			self.var_list.Select( item )
			#self.var_list.Focus( item )
		elif 	variable['name'] == 'content' and isinstance( self.rexObject, rex.publications.issue ):
			self.var_list.Select( item )
			#self.var_list.Focus( item )
		elif variable['name'] == 'first_name' and isinstance( self.rexObject, rex.contacts.contact ):
			self.var_list.Select( item )
			#self.var_list.Focus( item )
		elif variable['name'] == 'memberships' and isinstance( self.rexObject, rex.contacts.group ):
			self.var_list.Select( item )
			#self.var_list.Focus( item )
		elif variable['name'] == 'instance_name' and isinstance( self.rexObject, rex.binders.instance ):
			self.var_list.Select( item )
			#self.var_list.Focus( item )
		elif variable['name'] == 'body' and isinstance( self.rexObject, rex.dav.dav_item ):
			self.var_list.Select( item )
			#self.var_list.Focus( item )
		elif variable['name'] == 'id':
			self.var_list.Select( item )
			#self.var_list.Focus( item )

	def sortVariables( self, v1, v2 ):
		var1 = self.variables[ v1 ]
		var2 = self.variables[ v2 ]
		if var1['custom'] == False and var2['custom'] == False:
			return 0
		elif var1['custom'] == False and var2['custom'] == True:
			return -1
		elif var1['custom'] == True and var2['custom'] == False:
			return 1
		if var1['name'] > var2['name']:
			return 1
		if var1['name'] < var2['name']:
			return -1
		return 0
		
	def colorVariables( self ):
		#loop through the list items
		count = self.var_list.GetItemCount()
		if count < 1:
			common.dprint("No variables to colorize")
			return
		for i in range( 0, count ):
			var_id = self.var_list.GetItemData( i )
			var = self.variables[ var_id ]
			item = self.var_list.GetItem( i )
			if var['custom']:
				item.SetTextColour( wx.BLUE )
				self.var_list.SetItem( item )
			else:
				item.SetBackgroundColour( common.sui_colors('whitesmoke') )
				self.var_list.SetItem( item )

	def OnCloseMe(self, event):
		common.dprint("OnCloseMe")
		common.inspectorWindow = None
		self.rexObject = None
		self.Close(True)
	
	def OnClose(self,event):
		common.dprint("OnClose")
		event.Skip()
		
	def OnCloseWindow(self, event):
		common.dprint("OnCloseWindow")
		# print "OnCloseWindow"
		#common.inspectorWindow = None
		#self.rexObject = None
		#self.Destroy()
		self.Show(False)
		event.Skip(False)
